﻿using System.Text;
using System.ServiceModel;
using System.Xml;
using System.Xml.Serialization;
using APH.Parl2.Business.Publishing.DocBook;
using APH.Parl2.Shared.Contracts;
using System.IO;

namespace APH.Parl2.Business.Publishing
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, UseSynchronizationContext = false)]
    public class TranslationEngine : ITranslationEngine
    {
        [OperationBehavior]
        public TranslatedDocumentData TranslateDocument(IncomingDocumentData documentData)
        {
            var translatedData = new TranslatedDocumentData {Author = string.Empty};

            using (var stream = new MemoryStream(documentData.DocumentBytes))
            {
                var converter = new WordXmlToDocBookConverter(stream);
                var article = converter.Convert();

                var settings = new XmlWriterSettings { Indent = true, Encoding = Encoding.UTF8 };
                using (var sw = new StringWriterWithEncoding(Encoding.UTF8))
                {
                    using (var x = XmlWriter.Create(sw, settings))
                    {
                        var xs = new XmlSerializer(typeof(Article));
                        xs.Serialize(x, article);
                        x.Flush();
                    }
                    sw.Flush();
                    translatedData.DocumentXml = sw.ToString();
                    translatedData.Author = article.Info.Author.PersonName.FirstName + " " + article.Info.Author.PersonName.Surname;
                }
            }

            return translatedData;
        }
    }
}
